package com.uniview.controller;

import com.uniview.orm.model.City;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.core.ReactiveValueOperations;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @Author lux
 * @date: 2019/12/6
 * @desc:
 */
@RestController
@RequestMapping(value = "/city")
public class ReactiveController {
    @Autowired
    private ReactiveRedisTemplate reactiveRedisTemplate;

    @RequestMapping(value = "/get/{id}")
    public Mono<City> findCityById(@PathVariable("id") Long id) {
        String key = "city_" + id;
        ReactiveValueOperations<String, City> operations = reactiveRedisTemplate.opsForValue();
        Mono<City> city = operations.get(key).delaySubscription(Duration.ofSeconds(300));
        return city;
    }

    @RequestMapping("/save")
    public Mono saveCity(@RequestBody City city) {
        String key = "city_" + city.getId();
        ReactiveValueOperations<String, City> operations = reactiveRedisTemplate.opsForValue();
        Mono mono =operations.set(key,city);
        return mono;
    }

    @RequestMapping(value = "/delete/{id1}")
    public Mono<Long> deleteCity(@PathVariable("id1") Long id) {
        String key = "city_" + id;
        return reactiveRedisTemplate.delete(key);
    }

    @GetMapping("/")
    public Mono<City> getUser() {
        City city = new City();
        city.setId("1");
        city.setCityName("wuhan");
        return Mono.just(city);
    }
}
